package com.pw.gmall.realtime.utils;

import com.pw.gmall.realtime.annotation.NoSink;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: linux_future
 * @since: 2022/3/16
 **/
public class AtguiguUtils {


    public static <T> List<T> toList(Iterable<T> it) {
        ArrayList<T> result = new ArrayList<>();
        for (T t : it) {
            result.add(t);
        }
        return result;
    }


    public static String toDateTime(long time, String... format) {
        String f = "yyyy-MM-dd HH:mm:ss";
        if (format.length != 0) {
            f = format[0];
        }
        return new SimpleDateFormat(f).format(time);
    }

    public static String fieldsTOString(Field[] fields) {
        StringBuilder fieldsString = new StringBuilder();
        for (Field field : fields) {
            NoSink noSink = field.getAnnotation(NoSink.class);
            if(noSink==null) {
                fieldsString.append(field.getName() + ",");
            }
        }
        fieldsString.deleteCharAt(fieldsString.length() - 1);
        return fieldsString.toString();
    }

    public static long dateTimeToTs(String time, String... formatter) {
        String f = "yyyy-MM-dd HH:mm:ss";
        if (formatter.length != 0) {
            f = formatter[0];
        }
        long ts = 0L;

        try {
            ts = new SimpleDateFormat(f).parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ts;
    }

    /**
     * 分词去重
     * @param kw
     * @return
     */
    public static ArrayList<String> splitByIkAnalyze(String kw) {
        IKSegmenter seg = new IKSegmenter(new StringReader(kw), true);
        Collection<String> words = new HashSet<>();
        try {
            Lexeme next = seg.next();
            while (next != null) {
                String word = next.getLexemeText();
                words.add(word);
                next = seg.next();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>(words);
    }
}
